package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.CollectUtil;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.vo.JsonResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.Arrays;

@Path("/banner")
public class BannerController extends BaseController {

    public void list() {
        renderJson(JsonResult.successWithData(
                CollectUtil.convert(Db.find("select url,link from dctp_banner "), Record::toMap)));
    }

    @Before(Tx.class)
    public void save() {
        Record body = jsonBody();
        String banners = body.getStr("banners");
        if (StringUtil.isNotEmpty(banners)) {
            Db.delete("delete from dctp_banner ");
            Arrays.stream(banners.split(",")).forEach(banner -> {
                Record r = new  Record();
                r.set("url", banner);
                r.set("create_time", DateUtil.now())
                        .set("status",1);
                Db.save("dctp_banner", r);
            });
        }
        renderJson(JsonResult.success());
    }
}
